import { getUserMenuList } from '@/api/permission/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import router, { resetRouter } from '@/router'
import { roleList } from '@/utils/dynamicPermission'
import { MessageBox, Message } from 'element-ui'
import { logout } from 'igw-library/lib/sdk'
const state = {
	token: getToken(),
	name: '',
	avatar: '',
	introduction: '',
	roles: [],
	elePermissions: [],
	systemId: ''
}

const mutations = {
	SET_TOKEN: (state, token) => {
		state.token = token
	},
	SET_INTRODUCTION: (state, introduction) => {
		state.introduction = introduction
	},
	SET_NAME: (state, name) => {
		state.name = name
	},
	SET_AVATAR: (state, avatar) => {
		state.avatar = avatar
	},
	SET_ROLES: (state, roles) => {
		state.roles = roles
	},
	SET_ELEPERMISSION: (state, elePermissions) => {
		state.elePermissions = elePermissions
	},
	SET_SYETEM_ID: (state, systemId) => {
		state.systemId = systemId
	}
}

const actions = {

	// 获取用户信息,菜单列表，权限列表
	getInfo({ commit, state }) {
		return new Promise((resolve, reject) => {
			getUserMenuList({ systemCode: 'ItApp-ProductInfo-Management' }).then(res => {
				const data = {
					roles: ['*', ...roleList(res.data.body.menuList)], // 菜单权限
					name: res.data.body.userName, // 用户名
					avatar: require('@/assets/logo/userImg.jpg'), // 用户头像
					introduction: '景顺长城', // 用户个性签名
					elePermissions: res.data.body.permissions, // 元素权限
					menuList: res.data.body.menuList,
					systemId: res.data.body.roleList && res.data.body.roleList[0] && res.data.body.roleList[0].systemId
				}
				if (!res.data.body.menuList.length) {
					MessageBox({
						message: '该用户无任何页面资源，请联系系统管理员配置',
						showCancelButton: false,
						showClose: false,
						closeOnClickModal: false,
						closeOnPressEscape: false,
						confirmButtonText: '确定',
						title: '提示',
						type: 'warning'
					}).finally(() => {
						logout()
					})
					return
				}
				commit('SET_SYETEM_ID', data.systemId)
				commit('SET_ROLES', [...new Set(data.roles)])
				commit('SET_NAME', data.name)
				commit('SET_AVATAR', data.avatar)
				commit('SET_INTRODUCTION', data.introduction)
				commit('SET_ELEPERMISSION', data.elePermissions)
				resolve(data)
			}).catch(err => {
				Message({ message: '服务器报错，获取页面资源失败，请联系管理员', type: 'error' })
				reject(err)
			})
		})
	},

	// 删除令牌
	resetToken({ commit }) {
		return new Promise(resolve => {
			commit('SET_TOKEN', '')
			commit('SET_ROLES', [])
			removeToken()
			resolve()
		})
	},

	// 动态修改权限
	async changeRoles({ commit, dispatch }, role) {
		const token = role + '-token'
		commit('SET_TOKEN', token)
		setToken(token)
		const { roles } = await dispatch('getInfo')
		resetRouter()
		// 根据角色生成可访问的路线图
		const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })
		// 动态添加可访问的路线
		router.addRoutes(accessRoutes)
		console.log(router)
		// 重置访问的视图和缓存的视图
		dispatch('tagsView/delAllViews', null, { root: true })
	}

}

export default {
	namespaced: true,
	state,
	mutations,
	actions
}
